<!--
 * @Description: 
 * @Author: 张文韬
 * @Date: 2024-06-24 15:29:13
 * @LastEditTime: 2024-06-29 09:46:01
 * @LastEditors: 张文韬
 * @Reference: 
-->
<template>
  <el-card mt-10px>
    <BaseInfo ref="baseInfoRef" :dataSource="orderInfo.insureBase" @updateProduct="updateProduct" @priceChange="priceChange" />
  </el-card>
  <el-card mt-10px>
    <PolicyHolder ref="policyHolderRef" :dataSource="orderInfo.applicantInfo" @policyHolderTypeChange="policyHolderTypeChange" />
  </el-card>
  <el-card mt-10px>
    <Insurant ref="insurantRef" 
      :data="orderInfo.insuredList"
      :itemPrice="formData.itemPrice" 
      :policyHolderType="policyHolderType"
      :autoPolicy="formData.isAutoPolicy"
      :isHasPolicy="formData.isHasPolicy"
      :isMany="formData.isMany"
      @get-draft="getDraft" 
      @change-many="changeMany"
      @set-policy-holder="setPolicyHolder" />
  </el-card>
  <div class="m-30px text-center">
    <div class="flex justify-center items-center gap-10px">
      <el-checkbox v-model="formData.isCheck" label="我已阅读并同意" size="large" />
      <a class="text-blue"
        v-for="item in agreements"
        :href="item.url" 
        target="_blank" 
        onclick="window.event.cancelBubble=true"
      >{{ `《${item.name}》` }}</a>
    </div>
    <div class="m-10px">
      <el-button type="primary" :loading="loading" @click="save">确认投保</el-button>
    </div>
  </div>
  <PayQRCodeModal ref="paymentModalRef" @success="paySuccess" />
</template>

<script setup>
import PolicyHolder from '../PolicyHolder/index.vue'
import Insurant from '../Insurant/index.vue'
import BaseInfo from '../BaseInfo/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { bbOrderSave, getItem, getPayUrl } from '@/api/insurance'
import PayQRCodeModal from  '../PayQRCodeModal/index.vue'
// import DocView from '@/components/DocView/index.vue'
import { downBlobFile } from '/@/utils/other';

const emits = defineEmits(['updateProduct'])
const router = useRouter()

const props = defineProps({
  // loading: {
  //   type: Boolean,
  //   default: false
  // },
  data: {
    type: Array,
    default: () => []
  },
})

const route = useRoute()
const loading = ref(false)
const orderInfo = ref({})

const formData = reactive({
  product: {},
  isCheck: false,
  isAutoPolicy: true,
  isHasPolicy: false,
  isMany: false,

  itemPrice: 0
})

const baseInfoRef = ref(null)
const policyHolderRef = ref(null)
const insurantRef = ref(null)

const agreements = [
  // {
  //   name: '客户服务协议',
  //   url: 'https://www.baidu.com'
  // },
  {
    name: '客户告知书',
    url: 'https://beibaoxin.dsibc.com/file/客户告知书.pdf'
  },
  // {
  //   name: '互联网信息披露',
  //   url: 'https://www.baidu.com'
  // },
  {
    name: '投保须知',
    url: 'https://beibaoxin.dsibc.com/file/投保须知.pdf'
  },
  {
    name: '保险条款',
    url: 'https://beibaoxin.dsibc.com/file/平安境外旅行保险条款.pdf'
  },
]

const updateProduct = (product) => {
  console.log('updateProduct', product)
  formData.product = product
  emits('updateProduct', product)
}

const priceChange = (price) => {
  formData.itemPrice = price
}

const policyHolderType = ref('1')
const policyHolderTypeChange = async (type) => {
  if (type == 2) {
    // const data = await insurantRef.value.getData()
    // if (data && data.length > 0) {
    //   const holder = data.find(o => o.age >= 18)
    //   holder&&setPolicyHolder(holder)
    // }
    formData.isAutoPolicy = true
  } else {
    formData.isAutoPolicy = false
    policyHolderType.value = type
  }
}

const setPolicyHolder = (row) => {
  console.log('setPolicyHolder', row)
  // policyHolderRef.value.setPolicyHolder(row)
  formData.isHasPolicy = true
}

const paymentModalRef = ref()

let timer, times = 0
const save = async () => {
  console.log('save')
  
  if (!formData.isCheck) {
    return ElMessage.error('请先阅读并同意相关协议')
  }
  const baseInfo = await baseInfoRef.value.getData()
  if (!baseInfo) {
    return ElMessage.error('保险产品选项不完整')
  }
  const applicantInfo = await policyHolderRef.value.getData()
  if (!formData.isAutoPolicy && !applicantInfo) {
    return ElMessage.error('投保人信息不完整')
  }
  const insurantInfoList = await insurantRef.value.getData()
  if (!insurantInfoList) {
    return ElMessage.error('被保人信息不完整')
  }
  loading.value = true
  
  const params = {
    baseInfo,
    isMany: formData.isMany? 1 : 0,
    isAutoPolicy: formData.isAutoPolicy? 1 : 0,
    riskGroupInfo: { insurantInfoList }
  }
  if (route.query.mode == 'reboot' && route.query.id) {
    params.id = route.query.id
  }
  if (!formData.isAutoPolicy) {
    params.applicantInfo = applicantInfo
  }
  try {
    const { data: { id, payUrl, orderStatus, payChannelMsg, newUrl } } = await bbOrderSave(params)
    loading.value = false
    ElMessage.success('下单成功')
    if (orderStatus == 1) {
      ElMessage.success(payChannelMsg)
      finishPayment(newUrl, insurantInfoList)
    } else if (payUrl) {
      paymentModalRef.value.show(payUrl)
      timer = setInterval(async () => {
        if (times < 30) {
          const { data } = await getItem({ id })
          if (data.orderStatus == 1) {
            clearInterval(timer)
            finishPayment(newUrl, insurantInfoList)
          }
          times ++ 
        } else {
          clearInterval(timer)
        }
      }, 1000)
    }
  } catch (error) {
    loading.value = false
  }
}

const finishPayment = async (newUrl, insurantInfoList) => {
  if (newUrl && insurantInfoList && insurantInfoList.length) {
    ElMessageBox.confirm('要下载保单吗', '提示', {
      confirmButtonText: '下载',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      return downBlobFile(newUrl, null, `${insurantInfoList[0].name}${insurantInfoList.length>1?'等'+insurantInfoList.length+'人':'' }.pdf`);
    }).finally(() => {
      router.push({
        path: '/insurance/policy-manage/order/index',
      })
    });
  } else {
    ElMessage.warning('未返回保单链接')
    router.push({
      path: '/insurance/policy-manage/order/index',
    })
  }
}

const paySuccess = async () => {
  if (timer) {
    clearInterval(timer)
  }
  router.push({
    path: '/insurance/policy-manage/order/index',
  })
}

const changeMany = (val) => {
  formData.isMany = val
}

onMounted(() => {
  console.log('onMounted');
  const { id, mode } = route.query  
  if (id && mode == 'reboot') {
    getItem({ id }).then(({ data }) => {
      orderInfo.value = data
      formData.isMany = data.isMany == 1
      formData.isAutoPolicy = data.isAutoPolicy == 1
      // curProduct.value = res.data
    })
  }
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

const toLink = (link) => {
  console.log(link)
  window.open(link, '_blank')
}
const getDraft = (data) => {
  console.log('getDraft', data)
}

</script>